package com.puman.beautyfarmcounselor.ui.home;


import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.puman.beautyfarmcounselor.IndexActivity;
import com.puman.beautyfarmcounselor.MainActivity;
import com.puman.beautyfarmcounselor.R;
import com.puman.beautyfarmcounselor.http.AjaxCallBack;
import com.puman.beautyfarmcounselor.ui.core.BaseFragment;
import com.puman.beautyfarmcounselor.ui.customer.CustomerActivity;
import com.puman.beautyfarmcounselor.ui.customer.CustomerActivity_;
import com.puman.beautyfarmcounselor.ui.customer.CustomerDetailFragment_;
import com.puman.beautyfarmcounselor.ui.home.adpter.MemberVipListsAdapter;
import com.puman.beautyfarmcounselor.ui.home.model.CommunicateType;
import com.puman.beautyfarmcounselor.ui.home.model.FollowType;
import com.puman.beautyfarmcounselor.ui.home.model.TaskVipMember;
import com.puman.beautyfarmcounselor.ui.task.model.TaskMember;
import com.puman.beautyfarmcounselor.ui.task.swipemenulistview.SwipeMenu;
import com.puman.beautyfarmcounselor.ui.task.swipemenulistview.SwipeMenuCreator;
import com.puman.beautyfarmcounselor.ui.task.swipemenulistview.SwipeMenuItem;
import com.puman.beautyfarmcounselor.ui.task.swipemenulistview.SwipeMenuListView;
import com.puman.beautyfarmcounselor.util.MethedUtil;
import com.puman.beautyfarmcounselor.util.PublicData;
import com.puman.beautyfarmcounselor.util.XTHttp;
import com.puman.beautyfarmcounselor.util.config.GlobalData;
import com.puman.beautyfarmcounselor.util.config.RequestAddr;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;


/**
 * A placeholder fragment containing a simple view.
 */
@EFragment(R.layout.member_vip_list_layout)
public class MemberVipFragment extends BaseFragment implements com.puman.beautyfarmcounselor.util.view.SwipeRefreshLayout.OnLoadListener,com.puman.beautyfarmcounselor.util.view.SwipeRefreshLayout.OnRefreshListener{

    /**
     * init UI
     */
    @ViewById(R.id.back_btn)
    ImageView backBtn;
    @ViewById(R.id.base_title)
    TextView title;
    //    @ViewById(R.id.list)
//    ExpendListViewCompat mListView;
    @ViewById(R.id.listview)
    SwipeMenuListView listView;
    @ViewById(R.id.shotmessage_model)
    TextView shotMsgModel;
    @ViewById(R.id.tel_model)
    TextView telModel;

    @ViewById(R.id.swiperefresh)
    com.puman.beautyfarmcounselor.util.view.SwipeRefreshLayout swipeRefreshLayout;
    /**
     * init variables
     */

    private MemberVipListsAdapter memberVipListsAdapter;
    public boolean feedbackMsg = false;
    public boolean feedbackTel = false;
    public  String messageModelContent;
    String telModelContent;
    MemberVipFragment memberVipFragment;

    @FragmentArg
    String titleStr;
    @FragmentArg
    String taskFlag;  //1:生日提醒   2：院余提醒

    @AfterViews
    void updateView() {
        memberVipFragment = this;
        backBtn.setVisibility(View.VISIBLE);
        title.setText(titleStr);

        swipeRefreshLayout.setOnLoadListener(this);
        swipeRefreshLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
//        swipeRefreshLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        swipeRefreshLayout.setLoadNoFull(false);

        swipeRefreshLayout.setOnRefreshListener(this);

        /**
         * 设置layoutmanager
         */
        initSwipeView();

        getData();
    }

    String campainCode = "";
    XTHttp xtHttp = new XTHttp();
    String url = "";
    String param = "";
    private int pageNum = 1;

    private void getData() {
        param = "emp_id=" + GlobalData.counselor.getData().getEmployee_id() +
                "&page_number=" + pageNum;
        if (taskFlag.equals("1")) {
            url = RequestAddr.birthday + param;
        } else if (taskFlag.equals("2")) {
            url = RequestAddr.yuanyu + param;
        }
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealData(o);
                swipeRefreshLayout.setLoading(false);
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
                swipeRefreshLayout.setLoading(false);
                swipeRefreshLayout.setRefreshing(false);
//                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    TaskVipMember taskVipMember;

    private void dealData(Object object) {
        ObjectMapper mapper = new ObjectMapper();
//        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//        try {
//            taskVipMember = mapper.readValue(object.toString(), TaskVipMember.class);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (NullPointerException e) {
//            e.printStackTrace();
//        }

        try {
            JSONObject jsonObject = new JSONObject(object.toString());
            if (jsonObject.getBoolean("flag")) {
                if (taskVipMember == null || pageNum == 1){
                    taskVipMember = new TaskVipMember();
                }

                taskVipMember.setFlag(jsonObject.getBoolean("flag"));
                taskVipMember.setMsg(jsonObject.getString("msg"));
                JSONObject data = jsonObject.getJSONObject("data");
                JSONArray contentJsonArr = data.getJSONArray("comminicate_types");
                CommunicateType communicateType;
                for (int i = 0; i < contentJsonArr.length(); i++) {
                    communicateType = new CommunicateType();
                    JSONObject communicationTypeObj = contentJsonArr.getJSONObject(i);
                    communicateType.setCode(communicationTypeObj.getString("code"));
                    communicateType.setContent(communicationTypeObj.getString("content"));
                    communicateType.setName(communicationTypeObj.getString("name"));
                    communicateType.setTemplate_code(communicationTypeObj.getString("template_code"));
                    taskVipMember.getData().getComminicate_types().add(communicateType);
                }

                FollowType followType;
                JSONArray fllowTypeArr = data.getJSONArray("follow_list");
                for (int i = 0; i < fllowTypeArr.length(); i++) {
                    followType = new FollowType();
                    JSONObject followTypeObj = fllowTypeArr.getJSONObject(i);
                    try {
                        followType = mapper.readValue(followTypeObj.toString(), FollowType.class);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    taskVipMember.getData().getFollow_list().add(followType);
                }
            }else{
                Toast.makeText(getActivity(), "暂时没有跟进列表", Toast.LENGTH_LONG).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (taskVipMember == null) {
            return;
        }
        if (taskVipMember.isFlag()) {
//            MethedUtil.UtilToast(getActivity(), "list success");
            memberVipListsAdapter = new MemberVipListsAdapter(memberVipFragment, taskVipMember);
            listView.setAdapter(memberVipListsAdapter);
            memberVipListsAdapter.notifyDataSetChanged();
            for (int i = 0; i < taskVipMember.getData().getComminicate_types().size(); i++) {
                if (taskVipMember.getData().getComminicate_types().get(i).getTemplate_code().equals("0001")) {
                    shotMsgModel.setVisibility(View.VISIBLE);
                    messageModelContent = taskVipMember.getData().getComminicate_types().get(i).getContent();
                    feedbackMsg = true;
                }
                if (taskVipMember.getData().getComminicate_types().get(i).getTemplate_code().equals("0004")) {
                    telModel.setVisibility(View.VISIBLE);
                    telModelContent = taskVipMember.getData().getComminicate_types().get(i).getContent();
                    feedbackTel = true;
                }
            }

        } else {
//            MethedUtil.UtilToast(getActivity(), "list empty");
        }

    }

    private void initSwipeView() {
        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "delete" item
                SwipeMenuItem callItem = new SwipeMenuItem(
                        getActivity());
                // set item background
                callItem.setBackground(new ColorDrawable(Color.rgb(0xFf,
                        0x00, 0x00)));
                // set item width
                callItem.setWidth(dp2px(50));
                // callItem a icon
                callItem.setIcon(R.drawable.cell_select);
                // add to menu
                menu.addMenuItem(callItem);


            }
        };
        listView.setMenuCreator(creator);


        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        taskVipMember.getData().getFollow_list().get(position).setStatus(1);
                        memberVipListsAdapter.notifyDataSetChanged();
                        submitFeed(position);
                        break;
                }
                return false;
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MainActivity.getInstace().getSupportFragmentManager().beginTransaction()
                        .hide(memberVipFragment)
                        .replace(R.id.content_none_bottom,
                                CustomerDetailFragment_.builder().
                                        customerId(taskVipMember.getData().getFollow_list().get(position).getCustomer_id())
                                        .feedbackTel(feedbackTel)
                                        .feedbackMsg(feedbackMsg)
                                        .msgContent(messageModelContent)
                                        .build()).
                        addToBackStack(null).commit();
            }
        });
    }

    private void submitFeed(int position) {
        param = "emp_id=" + GlobalData.counselor.getData().getEmployee_id() +
                "&target_id=" + taskVipMember.getData().getFollow_list().get(position).getTarget_id() +
                "&type=" + 3;
        url = RequestAddr.feedNote + param;
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealFeed(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    PublicData publicData;

    private void dealFeed(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            publicData = mapper.readValue(object.toString(), PublicData.class);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        if (publicData == null) {
            return;
        }
        MethedUtil.UtilToast(getActivity(), publicData.getMsg());

    }

    @Click({R.id.back_btn, R.id.tel_model, R.id.shotmessage_model})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                MainActivity.getInstace().getSupportFragmentManager().popBackStack();
                break;
            case R.id.tel_model:
                showMsgTemplate("电话反馈模板", telModelContent);
                break;
            case R.id.shotmessage_model:
                showMsgTemplate("短信回馈模板", messageModelContent);
                break;
        }
    }

    private AlertDialog dlg;

    public void showMsgTemplate(String title, String content) {
        dlg = new AlertDialog.Builder(MainActivity.getInstace()).create();
        dlg.show();
        Window window = dlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.msgtemplate_dialog);
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);// 弹出键盘
        // 为确认按钮添加事件,执行退出应用操作
        TextView infoTitle = (TextView) window
                .findViewById(R.id.title_info); // 提示标题
        TextView infoContent = (TextView) window
                .findViewById(R.id.info_advice_text); // 提示标题
        ImageView closeBtn = (ImageView) window
                .findViewById(R.id.close_icon); // 提示标题
        TextView sureBtn = (TextView) window
                .findViewById(R.id.login_btn); // 提示标题
        infoTitle.setText(title);
        infoContent.setText(content);
        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
            }
        });
        sureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
            }
        });

    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    @Override
    public void onLoad() {
        pageNum++;
        getData();
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        getData();
    }
}
